<template>
  <div class="consultation-list-view">
    <div class="page-header">
      <h1 class="page-title">咨询总览</h1>
      <p class="page-subtitle">查找并管理您的法律咨询记录</p>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <div class="filter-left">
        <el-input
          v-model="searchQuery"
          placeholder="搜索咨询标题..."
          class="search-input"
          :prefix-icon="Search"
          clearable
          @input="handleSearch"
        />

        <el-select
          v-model="statusFilter"
          class="status-select"
          placeholder="咨询状态"
          clearable
          @change="handleFilter"
        >
          <el-option label="待接单" value="pending" />
          <el-option label="进行中" value="active" />
          <el-option label="已完成" value="completed" />
          <el-option label="已取消" value="cancelled" />
        </el-select>
      </div>

      <div class="filter-right">
        <el-button
          :type="showMyConsultations ? 'primary' : ''"
          @click="toggleMyConsultations"
          class="my-consultations-btn"
        >
          <el-icon><User /></el-icon>
          {{ showMyConsultations ? '全部咨询' : '我的咨询' }}
        </el-button>

        <el-button type="primary" @click="createNewConsultation">
          <el-icon><Plus /></el-icon>新建咨询
        </el-button>
      </div>
    </div>

    <!-- 咨询列表 -->
    <div class="consultation-list">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="consultations.length === 0" class="empty-state">
        <el-empty description="暂无咨询记录">
          <el-button type="primary" @click="createNewConsultation">开始第一次咨询</el-button>
        </el-empty>
      </div>

      <div v-else class="consultation-items">
        <div
          v-for="consultation in consultations"
          :key="consultation.id"
          class="consultation-item"
          @click="viewConsultationDetail(consultation.id)"
        >
          <div class="consultation-header">
            <h3 class="consultation-title">{{ consultation.title }}</h3>
            <div class="header-right">
              <el-tag :type="getStatusType(consultation.status)" size="small">
                {{ getStatusText(consultation.status) }}
              </el-tag>
              <span class="creator-info">
                创建者: {{ consultation.clientName || '未知用户' }}
              </span>
            </div>
          </div>

          <div class="consultation-info">
            <div class="info-item">
              <el-icon><User /></el-icon>
              <span>律师：{{ consultation.lawyerName || '待分配' }}</span>
            </div>
            <div class="info-item">
              <el-icon><Clock /></el-icon>
              <span>创建时间：{{ formatDate(consultation.createdAt) }}</span>
            </div>
            <div class="info-item">
              <el-icon><ChatDotRound /></el-icon>
              <span>消息数：{{ consultation.messageCount || 0 }}</span>
            </div>
            <div v-if="consultation.status === 'completed'" class="info-item rating-item">
              <el-icon><Star /></el-icon>
              <span>
                评分：
                <el-rate
                  v-model="consultation.rating"
                  disabled
                  size="small"
                  show-score
                  text-color="#ff9900"
                  score-template="{value} 分"
                />
              </span>
            </div>
          </div>

          <div
            v-if="consultation.status === 'completed' && consultation.review"
            class="review-preview"
          >
            <div class="review-label">用户评价：</div>
            <div class="review-text">{{ getReviewPreview(consultation.review) }}</div>
          </div>

          <div class="consultation-actions">
            <el-button size="small" @click.stop="viewConsultationDetail(consultation.id)">
              查看详情
            </el-button>

            <el-button
              v-if="isMyConsultation(consultation) && consultation.status === 'active'"
              type="success"
              size="small"
              @click.stop="enterChat(consultation.id)"
            >
              进入聊天
            </el-button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="total > 0" class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, inject, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, Plus, User, Clock, ChatDotRound, Star } from '@element-plus/icons-vue'
import { userInfoStore } from '@/stores/userinfo'

const router = useRouter()
const api = inject('$api')
const userStore = userInfoStore()

const loading = ref(false)
const consultations = ref([])
const searchQuery = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const showMyConsultations = ref(false)

// 防抖搜索
let searchTimeout = null

// 当前用户是否为律师
const isLawyer = computed(() => {
  return userStore.user?.role === 'LAWYER'
})

const getReviewPreview = (review) => {
  if (!review) return ''
  return review.length > 50 ? review.substring(0, 50) + '...' : review
}

const fetchConsultations = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      search: searchQuery.value,
      status: statusFilter.value,
    }

    if (showMyConsultations.value && userStore.user?.id && userStore.user.role === 'CLIENT') {
      params.clientId = userStore.user.id
    }

    if (showMyConsultations.value && userStore.user?.id && userStore.user.role === 'LAWYER') {
      params.lawyerId = userStore.user.id
    }

    const response = await api.consultation.getConsultations(params)

    if (response.code === 200) {
      consultations.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取咨询列表失败')
    }
  } catch (error) {
    console.error('获取咨询列表失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 筛选是否是当前用户的咨询
const isMyConsultation = (consultation) => {
  return (
    consultation.clientId === userStore.user?.id || consultation.lawyerId === userStore.user?.id
  )
}

const toggleMyConsultations = () => {
  showMyConsultations.value = !showMyConsultations.value
  currentPage.value = 1
  fetchConsultations()
}

const handleSearch = () => {
  clearTimeout(searchTimeout)
  searchTimeout = setTimeout(() => {
    currentPage.value = 1
    fetchConsultations()
  }, 500)
}

const handleFilter = () => {
  currentPage.value = 1
  fetchConsultations()
}

const handlePageChange = (page) => {
  currentPage.value = page
  fetchConsultations()
}

const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    active: 'primary',
    completed: 'success',
    cancelled: 'info',
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    pending: '待接单',
    active: '进行中',
    completed: '已完成',
    cancelled: '已取消',
  }
  return texts[status] || status
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString()
}

const createNewConsultation = () => {
  router.push('/consultation/create')
}

const viewConsultationDetail = (id) => {
  router.push(`/consultation/${id}`)
}

const enterChat = (id) => {
  router.push(`/consultation/${id}/chat`)
}

onMounted(() => {
  fetchConsultations()
})
</script>

<style scoped>
.consultation-list-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 统一页面标题样式 */
.page-header {
  margin-bottom: 30px;
  text-align: center;
}

.page-title {
  font-size: 2.5rem;
  color: #1a3a5f;
  margin: 15px 0 10px;
  font-weight: 700;
}

.page-subtitle {
  font-size: 1.1rem;
  color: #666;
  max-width: 600px;
  margin: 0 auto;
}

/* 统一筛选区域样式 */
.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: #f9fafb;
  border-radius: 8px;
  flex-wrap: wrap;
  gap: 15px;
}

.filter-left {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.search-input {
  width: 280px;
}

.status-select {
  width: 150px;
}

.filter-right {
  display: flex;
  gap: 10px;
}

/* 咨询列表样式 */
.consultation-list {
  min-height: 500px;
}

.loading-container {
  padding: 40px 0;
}

.empty-state {
  padding: 60px 0;
  text-align: center;
}

.consultation-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.consultation-item {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;
}

.consultation-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.consultation-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  gap: 10px;
}

.consultation-title {
  font-size: 1.3rem;
  color: #1a3a5f;
  margin: 0;
  flex: 1;
  font-weight: 600;
}

.header-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
  min-width: 120px;
}

.creator-info {
  font-size: 0.8rem;
  color: #999;
}

.consultation-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
  margin-bottom: 16px;
  padding: 12px;
  background: #f9fafb;
  border-radius: 8px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 0.9rem;
}

.rating-item {
  grid-column: 1 / -1;
  padding-top: 10px;
  border-top: 1px dashed #e0e0e0;
}

.rating-item :deep(.el-rate) {
  display: inline-flex;
  align-items: center;
}

.review-preview {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 16px;
  border-left: 3px solid #1a3a5f;
}

.review-label {
  font-weight: bold;
  color: #1a3a5f;
  font-size: 0.9rem;
  margin-bottom: 5px;
}

.review-text {
  color: #666;
  font-size: 0.9rem;
  line-height: 1.4;
}

.consultation-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}
</style>
